package com.app.controller;


import com.alibaba.fastjson.JSONObject;
import com.app.AppTools.AppConfigTools;
import com.app.AppTools.WechatTools;
import com.app.pojo.Result;
import com.app.pojo.User;
import com.app.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    WechatTools wechatTools;

    /**
     * 微信小程序的登陆，如果有账号，则返回登陆成功，如果没有则返回（首次用户，需要认证)
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        User u = userService.login(user);
        if(u != null){
            return Result.success();
        }else{
            return Result.error("登录失败");
        }
    }

    @PostMapping("/user")
    public Result add(@RequestBody User user){
        log.info("用户注册");
        userService.add(user);
        return Result.success();
    }

    @DeleteMapping("/user/{user_id}")
    public Result delete(@PathVariable int user_id){
        log.info("用户注销");
        userService.delete(user_id);
        return Result.success();
    }

    @PutMapping("/user")
    public Result update(@RequestBody User user){
        log.info("修改用户信息");
        userService.update(user);
        return Result.success();
    }

    @GetMapping("/user/{user_id}")
    public Result list(@PathVariable int user_id){
        log.info("查询用户信息");
        List<User> userList = userService.list(user_id);
        if(userList.isEmpty()){
            return Result.error("该用户不存在");
        }else{
            return Result.success(userList);
        }
    }

    @PostMapping("/getWxInfoTest")
    public String getWxInfoTest(@RequestBody JSONObject obj) {
        String AppId = AppConfigTools.getWxAppId();
        String AppSecret = AppConfigTools.getWxAppSecret();
        JSONObject wxJson = JSONObject.parseObject(WechatTools.getOpenid(obj.getString("code"), AppId, AppSecret));
        log.info("微信的返回值{}", wxJson);
        return wxJson.toJSONString();
    }
}